/**
 * 权限错误提示工具
 * 二次元粉色风格
 */

import { createApp, h } from 'vue'
import PermissionDeniedModal from '../components/PermissionDeniedModal.vue'

let modalInstance = null
let modalContainer = null

/**
 * 显示权限错误提示
 * @param {Object} options - 配置选项
 * @param {String} options.title - 标题
 * @param {String} options.message - 消息内容
 * @param {Function} options.onClose - 关闭回调
 */
export function showPermissionError(options = {}) {
  // 如果已经有实例，先销毁
  if (modalInstance) {
    hidePermissionError()
  }

  // 创建容器
  modalContainer = document.createElement('div')
  document.body.appendChild(modalContainer)

  // 默认配置
  const defaultOptions = {
    title: '权限不足 (｡•́︿•̀｡)',
    message: '抱歉～您没有访问此功能的权限哦',
    onClose: () => {}
  }

  const finalOptions = { ...defaultOptions, ...options }

  // 创建组件实例
  modalInstance = createApp({
    data() {
      return {
        show: true
      }
    },
    methods: {
      handleClose() {
        this.show = false
        setTimeout(() => {
          hidePermissionError()
          finalOptions.onClose()
        }, 300)
      }
    },
    render() {
      return h(PermissionDeniedModal, {
        modelValue: this.show,
        title: finalOptions.title,
        message: finalOptions.message,
        'onUpdate:modelValue': (val) => {
          this.show = val
        },
        onClose: this.handleClose
      })
    }
  })

  modalInstance.mount(modalContainer)
}

/**
 * 隐藏权限错误提示
 */
export function hidePermissionError() {
  if (modalInstance) {
    modalInstance.unmount()
    modalInstance = null
  }
  
  if (modalContainer && modalContainer.parentNode) {
    modalContainer.parentNode.removeChild(modalContainer)
    modalContainer = null
  }
}

/**
 * 根据HTTP状态码显示相应的错误提示
 */
export function showErrorByStatus(status, customMessage = null) {
  const errorMessages = {
    401: {
      title: '登录已过期 (｡•́︿•̀｡)',
      message: customMessage || '您的登录状态已过期，请重新登录～'
    },
    403: {
      title: '权限不足 (｡•́︿•̀｡)',
      message: customMessage || '抱歉～您没有访问此功能的权限哦\n请联系管理员获取相应权限'
    },
    404: {
      title: '找不到资源 (｡•́︿•̀｡)',
      message: customMessage || '抱歉～请求的资源不存在呢'
    },
    500: {
      title: '服务器错误 (｡•́︿•̀｡)',
      message: customMessage || '服务器出了点小问题～请稍后再试'
    }
  }

  const errorConfig = errorMessages[status] || {
    title: '操作失败 (｡•́︿•̀｡)',
    message: customMessage || '操作失败，请稍后重试～'
  }

  showPermissionError(errorConfig)
}

export default {
  show: showPermissionError,
  hide: hidePermissionError,
  showByStatus: showErrorByStatus
}
